package com.wjj.sixinone.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wjj.sixinone.common.enums.ExceptionEnum;
import com.wjj.sixinone.common.enums.UserEnum;
import com.wjj.sixinone.common.exception.GlobalException;
import com.wjj.sixinone.common.pojo.dto.UserDTO;
import com.wjj.sixinone.common.pojo.entity.User;
import com.wjj.sixinone.common.pojo.excel.UserExcel;
import com.wjj.sixinone.common.pojo.vo.UserFormVO;
import com.wjj.sixinone.common.pojo.vo.UserVO;
import com.wjj.sixinone.common.util.AuthContextUtil;
import com.wjj.sixinone.common.util.MD5Util;
import com.wjj.sixinone.common.util.Result;
import com.wjj.sixinone.handler.ExcelExportHandle;
import com.wjj.sixinone.mapper.UserMapper;
import com.wjj.sixinone.service.UserService;
import com.wjj.sixinone.service.minio.MinioFileService;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.commons.math3.genetics.Population;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

@Service

public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
    @Autowired
    private  UserMapper userMapper;
    @Autowired
    private RedisTemplate<String,String> redisTemplate;
    @Autowired
    private ExcelExportHandle excelExportHandle;
    @Autowired
    private MinioFileService minioFileService;

    @Override
    public Result selectUserByLimit(UserVO userVO) {
        int index = (userVO.getPage() - 1) * userVO.getLimit();
        UserDTO userDTO = new UserDTO();

        BeanUtils.copyProperties(userVO,userDTO);
        userDTO.setIndex(index);
        List<User> userList= userMapper.selectUserByLimit(userDTO);
        Integer count=userMapper.count(userDTO);
        return Result.ok().put("data", userList).put("count",count);
    }

    @Override
    public Result updateUserById(UserFormVO userVO) {
        User user=new User();
        String password = userMapper.selectOne(new LambdaQueryWrapper<User>().select(User::getPassword).eq(User::getId, userVO.getId())).getPassword();
        BeanUtils.copyProperties(userVO,user);

        if(!password.equals(userVO.getPassword())){
            String saltMD5 = MD5Util.getSaltMD5(userVO.getPassword());
            user.setPassword(saltMD5);
        }
        int i = userMapper.updateById(user);
        if (i==0){
            throw new GlobalException(ExceptionEnum.UPDATE_ERROR);
        }
        return Result.ok();
    }

    @Override
    public Result removeUserById(Integer id) {
        User user = userMapper.selectOne(new LambdaQueryWrapper<User>().eq(User::getId, id).select(User::getAvatar));
        String avatar = user.getAvatar();

        if (avatar!=null){
            minioFileService.deleteFileFromMinio(avatar);
        }
        int i = userMapper.deleteById(id);
        if (i==0){
            throw new GlobalException(ExceptionEnum.DELETE_ERROR);
        }
        return Result.ok();
    }

    @Override
    public Result addUser(UserFormVO userVO) {
        User userDb = userMapper.selectOne(new LambdaQueryWrapper<User>().select(User::getUsername).eq(User::getUsername, userVO.getUsername()));
        if (userDb!=null){
            throw new GlobalException(ExceptionEnum.USERNAME_EXIST);
        }

        String password = userVO.getPassword();
        String saltMD5 = MD5Util.getSaltMD5(password);
        User user=new User();
        BeanUtils.copyProperties(userVO,user);
        user.setPassword(saltMD5);

        String url = minioFileService.uploadBase64File(userVO.getImg());
        if(url==null){
            throw new GlobalException(ExceptionEnum.ERROR_MINIO_SEND);
        }
        user.setAvatar(url);


        if (userMapper.insert(user)==0){
            throw new GlobalException(ExceptionEnum.INSERT_ERROR);
        }
        return Result.ok();
    }

    @Override
    public void uploadExcel(HttpServletResponse response) {
        List<User> list = userMapper.selectList(new LambdaQueryWrapper<User>().select(User::getId,User::getUsername,User::getEmail,User::getUserRole,User::getCreateTime,User::getUpdateTime,User::getCreateUser,User::getUpdateUser).eq(User::getDeleted,0));

        List<UserExcel> userExcels = new ArrayList<>();
        for (User user : list) {
            UserExcel userExcel =  new UserExcel();
            BeanUtils.copyProperties(user, userExcel);
            userExcels.add(userExcel);
        }
        excelExportHandle.export(response, "管理员信息", userExcels, UserExcel.class);

    }

    @Override
    public Result logout(HttpServletRequest request) {
        String token = request.getHeader("Authorization");
        redisTemplate.delete(UserEnum.USER_ID.getKey()+token);
        AuthContextUtil.remove();
        return Result.ok();
    }
}
